import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { apiPost, apiPostWithResponse, batchOperations } from './apiHelper';
import { showError } from './errorHandler';

/**
 * 基础组件配置接口
 */
export interface BaseComponentConfig<T = any> {
  /** API端点 */
  apiEndpoint: string;
  /** 列表API端点 */
  listEndpoint?: string;
  /** 树形数据API端点 */
  treeEndpoint?: string;
  /** 所有数据API端点 */
  allDataEndpoint?: string;
  /** 默认分页大小 */
  defaultPageSize?: number;
  /** 是否支持树形视图 */
  supportTreeView?: boolean;
  /** 是否支持批量操作 */
  supportBatchOperations?: boolean;
  /** 是否支持导出 */
  supportExport?: boolean;
  /** 数据转换函数 */
  transformData?: (data: any[]) => any[];
  /** 导出配置 */
  exportConfig?: {
    headers: string[];
    transformData: (data: any[]) => any[];
  };
}

/**
 * 搜索表单接口
 */
export interface SearchForm {
  [key: string]: any;
}

/**
 * 分页接口
 */
export interface Pagination {
  currentPage: number;
  pageSize: number;
  total: number;
}

/**
 * 基础组件类
 */
export class BaseComponent<T = any> {
  // 响应式数据
  protected loading = ref(false);
  protected tableData = ref<T[]>([]);
  protected selectedRows = ref<T[]>([]);
  protected isTreeView = ref(false);
  protected searchForm: SearchForm;
  protected pagination: Pagination;

  // 配置
  protected config: BaseComponentConfig<T>;

  constructor(config: BaseComponentConfig<T>, initialSearchForm: SearchForm = {}) {
    this.config = config;
    this.searchForm = reactive(initialSearchForm);
    this.pagination = reactive({
      currentPage: 1,
      pageSize: config.defaultPageSize || 20,
      total: 0
    });
  }

  /**
   * 获取数据列表
   */
  async getDataList(): Promise<void> {
    this.loading.value = true;
    
    try {
      if (this.isTreeView.value && this.config.treeEndpoint) {
        // 树形视图
        const res = await apiPost<any>(this.config.treeEndpoint, {});
        if (res) {
          this.tableData.value = res.Data || [];
          this.pagination.total = res.Data?.length || 0;
        }
      } else {
        // 列表视图
        const params = this.buildQueryParams();
        const endpoint = this.config.listEndpoint || this.config.apiEndpoint + '/List';
        const res = await apiPost<any>(endpoint, params);
        
        if (res) {
          this.tableData.value = res.Data.list || [];
          this.pagination.total = res.Data.totalNumber || 0;
        }
      }
    } finally {
      this.loading.value = false;
    }
  }

  /**
   * 构建查询参数
   */
  protected buildQueryParams(): any {
    const params: any = {
      pageIndex: this.pagination.currentPage,
      pageSize: this.pagination.pageSize,
      SearchConditions: []
    };

    // 根据搜索表单构建查询条件
    Object.keys(this.searchForm).forEach(key => {
      const value = this.searchForm[key];
      if (value !== null && value !== undefined && value !== '') {
        params.SearchConditions.push({
          ConditionalModels: [{
            FieldName: key,
            FieldValue: value,
            ConditionalType: typeof value === 'string' ? 'Like' : 'Equal'
          }]
        });
      }
    });

    return params;
  }

  /**
   * 搜索
   */
  handleSearch(): void {
    this.pagination.currentPage = 1;
    this.getDataList();
  }

  /**
   * 重置搜索
   */
  handleReset(): void {
    Object.keys(this.searchForm).forEach(key => {
      this.searchForm[key] = null;
    });
    this.pagination.currentPage = 1;
    this.getDataList();
  }

  /**
   * 刷新
   */
  handleRefresh(): void {
    this.getDataList();
  }

  /**
   * 切换视图
   */
  toggleTreeView(): void {
    this.isTreeView.value = !this.isTreeView.value;
    
    if (this.isTreeView.value) {
      this.pagination.currentPage = 1;
    }
    
    ElMessage.success(this.isTreeView.value ? '已切换到树形视图' : '已切换到列表视图');
    this.getDataList();
  }

  /**
   * 删除项目
   */
  async handleDelete(item: T): Promise<void> {
    const success = await apiPostWithResponse(
      this.config.apiEndpoint + '/Update',
      { ...item, isDeleted: true },
      '删除成功',
      '删除失败'
    );
    
    if (success) {
      this.getDataList();
    }
  }

  /**
   * 批量操作
   */
  async handleBatchOperations(
    operation: (item: T) => any,
    confirmMessage: string,
    successMessage: string,
    errorMessage: string
  ): Promise<void> {
    try {
      const operations = this.selectedRows.value.map(item => 
        () => apiPost(this.config.apiEndpoint + '/Update', operation(item))
      );

      const success = await batchOperations(operations, successMessage, errorMessage);

      if (success) {
        this.getDataList();
      }
    } catch (error) {
      if (error !== 'cancel') {
        showError(error, errorMessage);
      }
    }
  }

  /**
   * 选择变化
   */
  handleSelectionChange(selection: T[]): void {
    this.selectedRows.value = selection;
  }

  /**
   * 分页大小变化
   */
  handleSizeChange(size: number): void {
    this.pagination.pageSize = size;
    this.pagination.currentPage = 1;
    this.getDataList();
  }

  /**
   * 当前页变化
   */
  handleCurrentChange(page: number): void {
    this.pagination.currentPage = page;
    this.getDataList();
  }

  /**
   * 获取计算属性
   */
  getComputedProps() {
    return {
      hasSelectedRows: computed(() => this.selectedRows.value.length > 0),
      showPagination: computed(() => !this.isTreeView.value),
      treeProps: computed(() => 
        this.isTreeView.value ? { children: 'Children', hasChildren: 'hasChildren' } : undefined
      )
    };
  }

  /**
   * 获取响应式数据
   */
  getReactiveData() {
    return {
      loading: this.loading,
      tableData: this.tableData,
      selectedRows: this.selectedRows,
      isTreeView: this.isTreeView,
      searchForm: this.searchForm,
      pagination: this.pagination
    };
  }

  /**
   * 获取方法
   */
  getMethods() {
    return {
      getDataList: this.getDataList.bind(this),
      handleSearch: this.handleSearch.bind(this),
      handleReset: this.handleReset.bind(this),
      handleRefresh: this.handleRefresh.bind(this),
      toggleTreeView: this.toggleTreeView.bind(this),
      handleDelete: this.handleDelete.bind(this),
      handleBatchOperations: this.handleBatchOperations.bind(this),
      handleSelectionChange: this.handleSelectionChange.bind(this),
      handleSizeChange: this.handleSizeChange.bind(this),
      handleCurrentChange: this.handleCurrentChange.bind(this)
    };
  }

  /**
   * 初始化
   */
  async init(): Promise<void> {
    await this.getDataList();
  }
}

/**
 * 创建基础组件的组合式函数
 */
export function useBaseComponent<T = any>(
  config: BaseComponentConfig<T>,
  initialSearchForm: SearchForm = {}
) {
  const component = new BaseComponent<T>(config, initialSearchForm);
  
  // 生命周期
  onMounted(() => {
    component.init();
  });

  return {
    ...component.getReactiveData(),
    ...component.getComputedProps(),
    ...component.getMethods()
  };
}
